/*
 * This file is a part of the RMI Plugin for Eclipse tutorials.
 * Copyright (C) 2002-7 Genady Beryozkin
 * 
 * You are free to modify this file, as long as you leave
 * the following copyright:
 * 
 * This file is based on the Remote File System example of
 * the RMI Plug-in for Eclipse. The original code is 
 * Copyright (C) 2002-7 Genady Beryozkin
 */
package rmi.filesystem.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;

import rmi.filesystem.common.IRemoteInputStream;


/**
 * A wrapper for a remote input stream. It extends {@link InputStream}
 * so it can be used in APIs that expect {@link InputStream} and can't 
 * work with our {@link IRemoteInputStream}. Notice the implementation
 * of {@link RemoteInputStreamWrapper#read(byte[], int, int)} that must
 * use {@link IRemoteInputStream#read(int)}.
 * 
 * @author Genady Beryozkin, rmi-info@genady.net
 */
public class RemoteInputStreamWrapper extends InputStream implements Serializable{

	IRemoteInputStream is;
	
	public RemoteInputStreamWrapper(IRemoteInputStream is) {
		this.is = is;
	}
	
	@Override
	public int read() throws IOException {
		return is.read();
	}
	
	@Override
	public int available() throws IOException {
		return is.available();
	}
	
	@Override
	public void close() throws IOException {
		is.close();
	}
	
	@Override
	public int read(byte[] b) throws IOException {
		return read(b, 0, b.length);
	}
	
	/*
	 * (non-Javadoc)
	 * @see java.io.InputStream#read(byte[], int, int)
	 * @see IRemoteInputStream#read(int)
	 */
	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		byte[] buf = is.readBytes(len);
		if (buf == null) {
			return -1;
		}
		System.arraycopy(buf, 0, b, off, buf.length);
		return buf.length;
	}
	
	@Override
	public long skip(long n) throws IOException {
		return is.skip(n);
	}
}
